package com.mustachio.urlshortener
{
	import com.mustachio.urlshortener.events.LinkEvent;
	
	import flash.display.Sprite;
	
	import mx.rpc.events.ResultEvent;
	import mx.rpc.http.HTTPService;
	
	public class URLShortenService extends Sprite
	{
		private static const serviceURL:String = "http://clicketysplit.com/api2/service/url_shorten.xml?callback=?";
		private var http:HTTPService;
		private var _shortURL:String;
		private var localLinkVO:LinkVO;
		public function URLShortenService(urlToShorten:String, incomingLinkVO:LinkVO)
		{
			localLinkVO = incomingLinkVO;
			/* if(urlToShorten.length > 19){ */
				var params:Object = new Object();
				params.url = urlToShorten;
				
				http = new HTTPService();
				http.method = "GET";
				http.url = serviceURL;
				http.showBusyCursor = true;
				http.resultFormat = "e4x";
				http.request = urlToShorten;
				http.addEventListener(ResultEvent.RESULT, resultHandler, false, 0, true);
				http.send(params);
			/* }else{
				localLinkVO.shortLink = urlToShorten;
				var evt:LinkEvent = new LinkEvent("URLShortenResponseEvent2", true, false);
				evt.linkVO = localLinkVO;
				dispatchEvent(evt);
			} */
		}
		
		public function resultHandler(e:ResultEvent):void{
			var xmlResult:XML = new XML();
			xmlResult = e.result as XML;
			
			_shortURL = "http://smi.sh/"+xmlResult.s_code;
			
			localLinkVO.shortLink = _shortURL;
			var evt:LinkEvent = new LinkEvent("URLShortenResponseEvent", false, false);
			evt.linkVO = localLinkVO;
			dispatchEvent(evt);
		}
		
		public function get shortURL():String{
			return _shortURL;
		}

	}
}